package com.uni.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uni.config.JWTProperties;
import com.uni.entity.Dto;
import com.uni.util.DtoUtil;
import com.uni.util.JWTConstants;
import com.uni.util.JWTUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 请求鉴权过滤器
 */
@Slf4j
@Component
public class AccessGateWayFilter implements GlobalFilter, Ordered {

    private ObjectMapper objectMapper;

    @Autowired
    private JWTProperties jwtProperties;

    @Autowired
    private AntPathMatcher antPathMatcher;

    public AccessGateWayFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();

        //跳过不需要验证的url
        for (String skip : jwtProperties.getSkipAuthUrls()) {
            if (antPathMatcher.match(skip, url))
                return chain.filter(exchange);
        }

        //获取token
        String token = exchange.getRequest().getHeaders().getFirst(JWTConstants.JWT_HEADER_KEY);
        ServerHttpResponse response = exchange.getResponse();

        if (StringUtils.isBlank(token)){
            //没有token
            return authError(response, "请登录");
        } else {
            try {
                //解析token
                Jws<Claims> claims = JWTUtils.parserToken(token, jwtProperties.getPublicKey());
                DateTime now = DateTime.now();
                DateTime exp = new DateTime(claims.getBody().getExpiration());

                log.info(claims.getBody().getExpiration().toString());

                /* jwt签名验证器 */
                DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(SignatureAlgorithm.RS256, jwtProperties.getPublicKey());
                String[] pre = token.split("\\.");
                String jwtWithoutSignature =  pre[0] + "." + pre[1];
                boolean valid = validator.isValid(jwtWithoutSignature, claims.getSignature());
                if (valid){ //签名验证通过
                    return chain.filter(exchange);
                }else {
                    return authError(response, "认证无效");
                }
            } catch (Exception e) {
                log.error("检查token时异常: " + e);
                if (e.getMessage().contains("JWT expired"))
                    return authError(response, "认证过期");
                else
                    return authError(response, "认证失败");
            }
        }
    }

    /**
     * 认证错误输出
     * @param response 响应对象
     * @param msg 错误信息
     * @return 响应信息
     */
    private Mono<Void> authError(ServerHttpResponse response, String msg) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        Dto returnFail = DtoUtil.returnFail(msg, HttpStatus.UNAUTHORIZED.toString());
        String returnStr = "";
        try {
            returnStr = objectMapper.writeValueAsString(returnFail);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer buffer = response.bufferFactory().wrap(returnStr.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(buffer));
    }


    @Override
    public int getOrder() {
        return -999;
    }
}
